package com.lagou.dao;

import com.lagou.bean.Class;
import com.lagou.util.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class ClassDaoImp implements ClassDao {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());

    /**
     * 自定义方法实现班级查找功能*/
    @Override
    public List<Class> findClass() {

        String sql = "select * from t_class";

        List<Class> query = null;
        try {
            query = qr.query(sql, new BeanListHandler<>(Class.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return query;

    }

    /**
     * 根据班级ID查找班级人数
     * @param id
     * @return
     */
    @Override
    public int StudentNum(int id) {
        String sql = "select count(*) from t_student where cid =?";
        Object query = null;
        try {
         query = qr.query(sql, new ScalarHandler<>(), id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        Number number = (Number) query;
        return  number.intValue();
    }
    /**
     * 根据请求的参数创建班级
     * @param classes
     * @return
     */
    @Override
    public int addClass(Class classes) {

        String sql = "insert into  t_class values (null,?,?,?,?)";
        Object[] params = {classes.getCname(),classes.getGrade(),classes.getTeacher(),classes.getSlogan()};
        int update = 0;
        try {
            update = qr.update(sql, params);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update;

    }
    /**
     * 根据课程删除班级
     * @param cname
     * @return
     */
    @Override
    public int delClass(String cname) {

        String sql = "SELECT COUNT(*)FROM t_student WHERE cid= (SELECT cid FROM t_class WHERE cname = ?)";
        String sql1 = "delete from t_class where cname = ?";
        int update = 0;
        try {
            Object query = qr.query(sql, new ScalarHandler<>(), cname);
            Number number = (Number)query;
            if(number.intValue()==0){
                update = qr.update(sql1, cname);
            }else{
                return 0;
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update;

    }
}

